Generic types are "erased" at compile time. The strong type checking in Kotlin
can use those generic types at compile time, but at runtime, the types are
no longer there. This has implications for cases where you need the actual
type at runtime, such as for is
checks.
One workaround is if you have an inline
function that uses a generic type.
You can add the reified
keyword before the type, and that tells the Kotlin
compiler to make that type available at runtime inside of that inline function.
So, in the example above, if we skip the reified
keyword, we will get a
compile error like "Cannot check for instance of erased type: T". But with
the reified
keyword, the code compiles and works. filterByType()
works
the same way that filterIsInstance()
does in the Kotlin standard library,
returning a subset of items that match the desired type.